import '../stylesheets/chat_reset.min.css'
import '../stylesheets/chat_style.css'
import {default as contract} from 'truffle-contract'
import create_users from '../../build/contracts/CreateUsers.json';
const  NodeRSA = require("node-rsa");

var User = contract(create_users);
User.setProvider(web3.currentProvider);

var imgUrl1 = require('../img/thomas.jpg');
var imgUrl2 = require('../img/michael-jordan.jpg');


var pastReceiver;
window.onload = function () {
    getFriends();
    addImg('p1_img', imgUrl2);
    pastReceiver = receiver;
};
// document.querySelector('.chat[data-chat=person2]').classList.add('active-chat');
// document.querySelector('.person[data-chat=person2]').classList.add('active');
//add user heard img
window.addImg = function (person, imgUrl) {
    var img = document.createElement('img');
    img.setAttribute('src', imgUrl);
    document.getElementById(person).appendChild(img)
};


window.chatClick = function (element) {
    var myDate = new Date(); //添加时间信息
    document.getElementById("nowtime").textContent = myDate.toLocaleString();
    var chat = document.getElementById("chat");
    chat.style.cssText = "display:block";
}

//删除历史数据
window.cleanInf = function () {

    var x = document.querySelectorAll('.inf')
    for (let i = 0; i < x.length; i++) {
        x[i].remove();
    }


    //显示获得历史数据按钮
    var gE = document.getElementById('getEvent');
    gE.style.cssText = 'display:block;margin: auto;';
}

//获取当前用户的好友名单
function getFriends() {
    User.deployed().then(function (i) {
        var add = getCookie("address");
        i.getFriendAddress(add).then(function (f) {
            if (f.length) {
                var list = f.split('/')
                /*下面是加载好友进入前端界面*/
                for (let j = 0; j < list.length; j++) {
                    if (list[j] != '') {
                        i.getAccountByAddress.call(list[j]).then(function (g) {
                            var imgUrl2 = require('../img/dog.png');
                            var li = document.createElement("li");
                            li.setAttribute("class", "person");
                            li.setAttribute("data-chat", "person2");
                            li.setAttribute("value", list[j]);
                            li.setAttribute("onclick", "getV(this);chatClick(this);cleanInf()")
                            var div = document.createElement("div");
                            div.id = "p2_img";
                            div.style.cssText = "width: 40px;height: 40px;float: left;";
                            var div2 = document.createElement("div")
                            var span = document.createElement("span")
                            span.setAttribute("class", "name")
                            span.innerText = g[3];
                            var span2 = document.createElement("span");
                            span2.setAttribute("class", "time");
                            span2.innerText = '2:25PM';
                            var span3 = document.createElement("span");
                            span3.setAttribute("class", "preview");
                            span3.innerText = '你好！';
                            div2.appendChild(span);
                            div2.appendChild(span2);
                            div2.appendChild(span3);
                            li.appendChild(div);
                            li.appendChild(div2);
                            document.getElementById("p").appendChild(li);
                            addImg("p2_img", imgUrl2);
                        });
                    }
                }
            } else {
                console.log("no friend!")
            }

        })

    })
};

//获得当前地址信息；
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

    if (arr = document.cookie.match(reg))

        return unescape(arr[2]);
    else
        return null;
}

//表情包
// 将表情转为字符
// var str = "表情😀123456"
// console.log(str)

function utf16toEntities(str) {
    var patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
    str = str.replace(patt, function (char) {
        var H, L, code;
        if (char.length === 2) {
            H = char.charCodeAt(0); // 取出高位
            L = char.charCodeAt(1); // 取出低位
            code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法
            return "&#" + code + ";";
        } else {
            return char;
        }
    });
    return str;
}

// var str01 = utf16toEntities(str)
// console.log(str01)


var s = "&#128512;";//codePoint十进制值
// 将字符转为表情
function uncodeUtf16(str) {
    var reg = /\&#.*?;/g;
    var result = str.replace(reg, function (char) {
        var H, L, code;
        if (char.length == 9) {
            code = parseInt(char.match(/[0-9]+/g));
            H = Math.floor((code - 0x10000) / 0x400) + 0xD800;
            L = (code - 0x10000) % 0x400 + 0xDC00;
            return unescape("%u" + H.toString(16) + "%u" + L.toString(16));
        } else {
            return char;
        }
    });
    return result;
};
// var str02 = uncodeUtf16(s)
// console.log(str02)
var flag = 1;
window.showEmotion = function(rownumber) {
    if(flag == 1) {
        showEmotionDiv();
        var url = "https://emoji-api.com//categories/smileys-emotion?access_key=220f9a8d08401c7384c8197d531349658b5f11df";
//步骤一:创建异步对象
        var ajax = new XMLHttpRequest();
//步骤二:设置请求的url参数,参数一是请求的类型,参数二是请求的url,可以带参数,动态的传递参数starName到服务端
        ajax.open('get', url);
//步骤三:发送请求
        ajax.send();
//步骤四:注册事件 onreadystatechange 状态改变就会调用
        ajax.onreadystatechange = function () {

            if (ajax.readyState == 4 && ajax.status == 200) {
                //步骤五 如果能够进到这个判断 说明 数据 完美的回来了,并且请求的页面是存在的
                // console.log(ajax.responseText);//输入相应的内容
                var text = JSON.parse(ajax.responseText)
                // document.getElementById('text').textContent =text[0]['codePoint'];
                var number = 0;
                for (let i = 0; i < rownumber; i++) {
                    var table = document.getElementById('table');
                    var row = table.insertRow(i);
                    for (let j = 0; j < 10; j++) {
                        var cell = row.insertCell(j)
                        var num_ten = Number(parseInt((text[number++]['codePoint']), 16).toString(10))
                        var st = '&#' + num_ten + ';';
                        var str03 = uncodeUtf16(st);
                        cell.setAttribute("value", st);
                        cell.setAttribute('onclick', 'addEmotion(this)')
                        cell.innerHTML = str03
                    }
                }
            }
        }
        flag = 2;
    }else {

        document.getElementById("table").innerHTML="";
        document.getElementById("emotion").style.display="none";//显示
        flag = 1;
    }

}

//显示表情div
function showEmotionDiv(){
    document.getElementById("emotion").style.display="block";//显示
}

//点击表情后，追加表情到input框
window.addEmotion = function (element) {
    var str = element.getAttribute('value');
    var emotion = uncodeUtf16(str);
    var textObject = document.getElementById('noteInput');
    console.log(textObject.value)
    var text = textObject.value + emotion;
    textObject.value = text;
};


var keys={
    "pubkey":"",
    "prikey":""
}
//产生公私钥
window.pruduceKey = function () {
    var address = getCookie("address");
    generateKeyPair()//获取公私钥
    document.getElementById('pubkey').value = keys['pubkey'];
    document.getElementById('prikey').value = keys['prikey'];
    //判断密钥发生变化，提示用户保存密钥
    var v = getkey("pubkey");
    if (v != keys['pubkey']){
        alert("密钥已经更改，建议重新保存密码！！！")
    }
}
//实现公私钥的拷贝
document.querySelector("#pubkey").onclick = function() {
    var text = document.getElementById('pubkey').value;
    if (text){
        document.querySelector("#pubkey").select();
        document.execCommand('copy');
        alert("拷贝成功，请注意保存！！")
    }

};
document.querySelector("#prikey").onclick = function() {
    var text = document.getElementById('prikey').value;
    if (text) {
        document.querySelector("#prikey").select();
        document.execCommand('copy');
        alert("拷贝成功，请注意保存！！")
    }
};

function generateKeyPair(pkcsType,pkcsSize) {
    pkcsType = pkcsType ? pkcsType : 'pkcs8';//不为空则 设置为传入参数，为空则 设置为 pkcs8
    console.log('pkcsType=' + pkcsType);
    pkcsSize = pkcsSize || 512;
    //1.创建RSA对象，并指定 秘钥长度
    var key = new NodeRSA({b: pkcsSize});
    key.setOptions({encryptionScheme: 'pkcs1'});//指定加密格式

    //2.生成 公钥私钥，使用 pkcs8标准，pem格式
    var publicPem = key.exportKey(pkcsType + '-public-pem');//制定输出格式
    var privatePem = key.exportKey(pkcsType + '-private-pem');
    //console.log(key.$options);
    // console.log(pkcsType + '公钥:\n', publicPem);
    // console.log(pkcsType + '私钥:\n', privatePem);
    // //公钥加密
    // const privateKey = new NodeRSA(privatePem);
    // privateKey.setOptions({encryptionScheme: 'pkcs1'})
    // var encryData = key.encrypt('服务端测试 -> jameszou love code~~~', 'base64', 'utf8');
    // console.log('\n私钥加密后的数据：\n', encryData); //加密后数据为 base64 编码
    keys['pubkey'] = publicPem;
    keys['prikey'] = privatePem;
}

document.querySelector("#encrypt").onclick = function () {
    var add = getCookie("address");
    var publickey = document.getElementById('pubkey').value;
    console.log(publickey)
    User.deployed().then(function (i) {
        i.addPublickey(publickey,{
            from:add,
            gas:500000
        }).then( (res) =>{
            if (res){
                alert("加密成功！！");
            }else {
                console.log('err')
            }
        });
    });
};
//关闭或者打开解密窗口
window.encryptFlag =0;
window.openAndCloseEncrypt = function () {
    var openAndClose = document.getElementById('encode');
    if (encryptFlag ==0){
        openAndClose.style.display = 'block';
        encryptFlag =1;
    }else {
        openAndClose.style.display = 'none';
        encryptFlag = 0;
    }
}

//保存密钥
window.storageKey = function () {
    var pubkey = document.getElementById('pubkey').value;
    var prikey = document.getElementById('prikey').value;
    storageKey("pubkey",pubkey);
    storageKey("prikey",prikey);
    alert("保存内容成功")
}
function storageKey(keyname,data) {
    if(!window.localStorage){
        alert("浏览器支持localstorage");
    }else{
        var storage=window.localStorage;
        var k = keyname;
        storage.setItem(k,data);
    }
}

window.importkey = function () {
    var pubKey = getkey("pubkey");
    var prikey = getkey("prikey");
    document.getElementById('pubkey').value = pubKey;
    document.getElementById('prikey').value = prikey;
}
function getkey(k) {
    if(!window.localStorage){
        alert("浏览器支持localstorage");
    }else {
        var storage = window.localStorage;
        var v = storage.getItem(k);
        return v;
    }
}




